package com.sfac.day03.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@WebFilter(filterName = "parameterFilter",urlPatterns = "/*")
public class ParameterFilter implements Filter {
    private final static Logger LOGGER = LoggerFactory.getLogger(ParameterFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("==== Init Parameter filter ====");
        Filter.super.init(filterConfig);

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        LOGGER.debug("==== Destroy Parameter Filter ====");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        HttpServletRequestWrapper httpServletRequestWrapper =
                new HttpServletRequestWrapper(httpServletRequest){
            @Override
            public String getParameter(String name){
                String value = super.getParameter(name);
                if (StringUtils.isBlank(value)){
                    return "";
                }else {
                    return value.replaceAll("fuck","***");
                }
            }
                    @Override
                    public String[] getParameterValues(String name) {
                        String[] values = super.getParameterValues(name);
//                        List<String> temp = new ArrayList<>();
//                        for (String value : values) {
//                            temp.add(value.replaceAll("fuck", "***"));
//                        }
//                        return temp.toArray(new String[temp.size()]);

                        return Arrays.asList(values).stream()
                                .map(item -> item.replaceAll("fuck", "***"))
                                .toArray(String[] :: new);
                    }
                };

        filterChain.doFilter(httpServletRequestWrapper,httpServletResponse);
    }

    @Override
    public void destroy() {
        LOGGER.debug("==== Destroy Parameter Filter ====");

    }
}
